﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using Billing.Utilities;
using System.Data;
using Billing.Controls;
using System.Configuration;
using System.Drawing.Printing;

namespace Billing.Windows
{
    public class BOBDetails
    {
        public string CustomerName { get; set; }
        public string PhoneNumber { get; set; }
        public DateTime DeliveryDate { get; set; }
        public string DeliveryTime { get; set; }
        public string DeliveryPlace { get; set; }
        public string AdditionalDetails { get; set; }

        public int Qty { get; set; }
        public double EachBoxCost { get; set; }
        public double TotalAmt { get; set; }
        public double Advance { get; set; }
        public double Balance { get; set; }
        public double DiscountByCost { get; set; }
        public double DiscountByPercentage { get; set; }
        public string DiscountReason { get; set; }
        public double FinalDiscAmt { get; set; }
    }

    public partial class BulkOrderBoxBillingGrid : Window
    {
        BOBDetails bobDetails = new BOBDetails();
        public BulkOrderBoxBillingGrid()
        {
            InitializeComponent();
            lbBillingGrid.Items.Add(new BulkOrderBoxBillingGridItemControl());
            lbBillingGrid.SelectedIndex = 0;
            UpdateBillItemsSlNo();
        }

        void UpdateBillItemsSlNo()
        {
            try
            {
                int SlNo = 1;
                foreach (BulkOrderBoxBillingGridItemControl itemControl in lbBillingGrid.Items)
                {
                    itemControl.lblSrNo.Content = SlNo++;
                }
            }
            catch (Exception) { }
        }

        private void Window_KeyUp(object sender, KeyEventArgs e)
        {
            UpdateBillItemsSlNo();
            if (e.Key == Key.Escape)
            {
                if (lbBillingGrid.Items.Count > 0)
                {
                    if (MessageBoxResult.OK == MessageBox.Show("Do you want to close?", "Closing", MessageBoxButton.OKCancel, MessageBoxImage.Question))
                        this.Close();
                }
                else
                    this.Close();
            }
            else if (e.Key == Key.F2)
            {
                new BulkOrderBoxDetails(bobDetails).ShowDialog();
                customerName.Content = bobDetails.CustomerName;
                phoneNo.Content = bobDetails.PhoneNumber;
                deliveryDate.Content = bobDetails.DeliveryDate.ToString("dd-MMM-yyyy");
                deliveryPlace.Content = bobDetails.DeliveryPlace;
                deliverytime.Content = bobDetails.DeliveryTime;
                description.Content = bobDetails.AdditionalDetails;
            }
            else if (e.Key == Key.F3)
            {
                new BulkOrderBoxCostDetails(bobDetails).ShowDialog();
                advanceAmt.Content = bobDetails.Advance.ToString();
                balanceAmt.Content = bobDetails.Balance.ToString();
                discount.Content = bobDetails.FinalDiscAmt;
                lblFinalPrice.Content = bobDetails.TotalAmt;
            }
            else if (e.Key == Key.F1)
            {
                if (bobDetails.PhoneNumber == null || bobDetails.PhoneNumber == string.Empty)
                {
                    new BulkOrderBoxDetails(bobDetails).ShowDialog();
                    customerName.Content = bobDetails.CustomerName;
                    phoneNo.Content = bobDetails.PhoneNumber;
                    deliveryDate.Content = bobDetails.DeliveryDate.ToString("dd-MMM-yyyy");
                    deliveryPlace.Content = bobDetails.DeliveryPlace;
                    deliverytime.Content = bobDetails.DeliveryTime;
                    description.Content = bobDetails.AdditionalDetails;
                }
                else if (!(bobDetails.EachBoxCost > 0 && bobDetails.Qty > 0))
                {
                    new BulkOrderBoxCostDetails(bobDetails).ShowDialog();
                    advanceAmt.Content = bobDetails.Advance.ToString();
                    balanceAmt.Content = bobDetails.Balance.ToString();
                    discount.Content = bobDetails.FinalDiscAmt;
                    lblFinalPrice.Content = bobDetails.TotalAmt;
                }
                else
                {
                    new Confirm().ShowDialog();

                    if (Storage.IsValid)
                    {
                        bool isItemsRemoved = false;
                        for (int i = 0; i < lbBillingGrid.Items.Count; i++)
                        {
                            BulkOrderBoxBillingGridItemControl item = lbBillingGrid.Items[i] as BulkOrderBoxBillingGridItemControl;
                            if (item.txtQty.Text == "0" || item.txtQty.Text == string.Empty)
                            {
                                lbBillingGrid.Items.Remove(lbBillingGrid.Items[i]);
                                isItemsRemoved = true;
                                i -= 1;
                            }
                        }
                        if (isItemsRemoved)
                            UpdateBillItemsSlNo();

                        string BillNo = Database.GenerateBillForBulkOrder(lbBillingGrid.Items, bobDetails.TotalAmt, bobDetails.PhoneNumber, bobDetails.DeliveryDate, bobDetails.AdditionalDetails, bobDetails.Advance.ToString(), bobDetails.Balance.ToString(), bobDetails.DiscountByCost.ToString(), bobDetails.DiscountByPercentage.ToString(), bobDetails.DiscountReason, bobDetails.CustomerName, bobDetails.DeliveryTime, bobDetails.DeliveryPlace, 2, bobDetails.EachBoxCost, bobDetails.Qty);
                        //string BillNo = Database.GenerateBillForBulkOrder(lbBillingGrid.Items, double.Parse(lblFinalPrice.Content.ToString()), PhoneNumberEntered, DeliveryDateEntered, AdditionalDescEntered, Advance.ToString(), Balance.ToString(), DiscountByCost.ToString(), DiscountByPercentage.ToString(), DiscountReason, CustomerName, DeliveryTime, DeliveryPlace);
                        //this.TotalAmount = double.Parse(lblFinalPrice.Content.ToString());

                        if (PrintCommon.PrintItems != null)
                            PrintCommon.PrintItems.Clear();
                        if (PrintCommon.CreditNoteItems != null)
                            PrintCommon.CreditNoteItems.Clear();
                        if (PrintCommon.BulkOrderItems != null)
                            PrintCommon.BulkOrderItems.Clear();
                        if (PrintCommon.VendorItems != null)
                            PrintCommon.VendorItems.Clear();

                        foreach (BulkOrderBoxBillingGridItemControl item in lbBillingGrid.Items)
                        {
                            PrintCommon.BulkOrderItems.Add(new BulkOrderBillingGridItemControl { txtCode = item.txtCode, txtDesc = item.txtDesc, txtPrice = null, txtQty = item.txtQty, lblSrNo = item.lblSrNo, acceptNegativeStock = item.acceptNegativeStock, grp = item.grp });
                        }
                        PrintCommon.TotalAmt = bobDetails.TotalAmt;
                        Storage.IsFirstBill = false;
                        Storage.CreditNoteCompany = string.Empty;
                        Storage.BillNo = BillNo;

                        if (ConfigurationManager.AppSettings["PrinterType"] != null && ConfigurationManager.AppSettings["PrinterType"].ToString() == "new")
                        {
                            NewBulkPrinter form = new NewBulkPrinter(Storage.BillNo);
                            form.printDocument1.PrintController = new StandardPrintController();
                            form.printDocument1.Print();
                        }
                        else
                        {
                            OldBulkPrinter form = new OldBulkPrinter(Storage.BillNo);
                            form.printDocument1.PrintController = new StandardPrintController();
                            form.printDocument1.Print();
                        }

                        if (BillNo == string.Empty)
                        {
                            MessageBox.Show("Some Exception Has Occurred. Please try again later.", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                            return;
                        }
                        else
                        {
                            //MessageBox.Show("Bill Generated Successfully.", "Success", MessageBoxButton.OK, MessageBoxImage.Information);
                            this.Close();
                        }
                    }
                }
            }
        }

        BulkOrderBoxBillingGridItemControl GetSelectedItem()
        {
            try
            {
                return lbBillingGrid.SelectedItem as BulkOrderBoxBillingGridItemControl;
            }
            catch (Exception)
            {
                return null;
            }
        }

        private bool SetSelectedIndexForEmptyItem()
        {
            foreach (BulkOrderBoxBillingGridItemControl item in lbBillingGrid.Items)
            {
                if (item.txtCode.Text.ToString() == string.Empty || item.txtQty.Text.ToString() == string.Empty)
                {
                    lbBillingGrid.SelectedItem = item;
                    (lbBillingGrid.SelectedItem as BulkOrderBoxBillingGridItemControl).txtCode.Focus();
                    return true;
                }
            }
            return false;
        }

        private void SetLastSelectedItem()
        {
            try
            {
                lbBillingGrid.SelectedIndex = lbBillingGrid.Items.Count - 1;
            }
            catch (Exception) { }
        }

        private void lbBillingGrid_PreviewKeyUp(object sender, KeyEventArgs e)
        {
            try
            {
                if (e.Key == Key.Enter && GetSelectedItem().txtQty.IsFocused)
                {
                    BulkOrderBoxBillingGridItemControl item = (lbBillingGrid.SelectedItem as BulkOrderBoxBillingGridItemControl);
                    double value;
                    if (!(double.TryParse(item.txtQty.Text, out value)))
                    {
                        if (item.txtQty.Text != string.Empty)
                        {
                            MessageBox.Show("Invalid Quantity Field", "Invalid Qty", MessageBoxButton.OK, MessageBoxImage.Error);
                            item.txtQty.Clear();
                        }
                        return;
                    }

                    if (!(SetSelectedIndexForEmptyItem()))
                    {
                        lbBillingGrid.Items.Add(new BulkOrderBoxBillingGridItemControl());
                        SetLastSelectedItem();
                    }
                }
                else if (e.Key == Key.Up)
                {
                    BulkOrderBoxBillingGridItemControl item = lbBillingGrid.SelectedItem as BulkOrderBoxBillingGridItemControl;
                    double value;
                    if (!(double.TryParse(item.txtQty.Text, out value)))
                    {
                        if (item.txtQty.Text != string.Empty)
                        {
                            MessageBox.Show("Invalid Quantity Field", "Invalid Qty", MessageBoxButton.OK, MessageBoxImage.Error);
                            item.txtQty.Clear();
                        }
                        return;
                    }

                    lbBillingGrid.SelectedIndex = lbBillingGrid.SelectedIndex > 0 ? lbBillingGrid.SelectedIndex - 1 : 0;
                    item = lbBillingGrid.SelectedItem as BulkOrderBoxBillingGridItemControl;
                    if (item != null)
                    {
                        item.txtQty.Focus();
                        item.txtQty.SelectAll();
                    }
                }
                else if (e.Key == Key.Down)
                {
                    BulkOrderBoxBillingGridItemControl item = lbBillingGrid.SelectedItem as BulkOrderBoxBillingGridItemControl;
                    double value;
                    if (!(double.TryParse(item.txtQty.Text, out value)))
                    {
                        if (item.txtQty.Text != string.Empty)
                        {
                            MessageBox.Show("Invalid Quantity Field", "Invalid Qty", MessageBoxButton.OK, MessageBoxImage.Error);
                            item.txtQty.Clear();
                        }
                        return;
                    }
                    lbBillingGrid.SelectedIndex = lbBillingGrid.SelectedIndex > -1 ? lbBillingGrid.SelectedIndex + 1 : 0;
                    item = lbBillingGrid.SelectedItem as BulkOrderBoxBillingGridItemControl;
                    if (item != null)
                    {
                        item.txtQty.Focus();
                        item.txtQty.SelectAll();
                    }
                }
                else if (e.Key == Key.Left)
                {
                    BulkOrderBoxBillingGridItemControl item = lbBillingGrid.SelectedItem as BulkOrderBoxBillingGridItemControl;
                    if (item != null)
                    {
                        item.txtCode.Focus();
                        item.txtCode.SelectAll();
                    }
                }
                else if (e.Key == Key.Right)
                {
                    BulkOrderBoxBillingGridItemControl item = lbBillingGrid.SelectedItem as BulkOrderBoxBillingGridItemControl;
                    if (item != null)
                    {
                        item.txtQty.Focus();
                        item.txtQty.SelectAll();
                    }
                }
            }
            catch (Exception) { }
        }
    }
}
